package com.fruits.controller;
import com.fruits.domain.User;
import com.fruits.service.UserService;
import com.fruits.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();
   public String login(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        //1.获取参数
        String str =request.getParameter("str");
        String pwd = request.getParameter("pwd");
        //2.调用service
       User loginUser = userService.login(str, pwd);
       if(loginUser!=null){
           HttpSession session = request.getSession();
           session.setAttribute("user",loginUser);
           //重定向到首页
          // response.sendRedirect(request.getContextPath()+"/index.jsp");
           return "redirect:/index.jsp";
       } else{
           //转发到注册页面
           //request.getRequestDispatcher("/login.jsp").forward(request,response);
           return "forward:/login.jsp";
       }


   }


    public String register(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        // 1.获取参数
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String pwd1 = request.getParameter("pwd1");
        //2.封装对象
        User user = new User(email, phone, pwd1);
        //3.调用service保存
        User loginUser = userService.add(user);
        if(loginUser!=null){
            HttpSession session = request.getSession();
            session.setAttribute("user",loginUser);
            //重定向到首页
           // response.sendRedirect(request.getContextPath()+"/index.jsp");

            return "redirect:/index.jsp";
        } else{
            //转发到注册页面
           // request.getRequestDispatcher("/reg.jsp").forward(request,response);
            return "forward:/reg.jsp";
        }

    }
    public String add(HttpServletRequest request, HttpServletResponse response){
       String email = request.getParameter("email");
       String phone = request.getParameter("phone");
       String pwd = request.getParameter("pwd");
       User user = new User(email, phone, pwd);
       userService.add(user);
       return "redirect:/userServlet?method=findAll";
    }
    public String findAll(HttpServletRequest request, HttpServletResponse response){
        List<User> users = userService.findAll();
        request.setAttribute("users",users);
        return "forward:/allUser.jsp";
    }

}